package com.jhoncy.myproject.system.service;

import com.jhoncy.myproject.system.entity.SysRole;
import com.jhoncy.myproject.system.entity.SysUserRole;
import com.jhoncy.myproject.system.mapper.SysRoleMapper;
import com.jhoncy.myproject.system.mapper.SysUserRoleMapper;
import com.jhoncy.myproject.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
 * @author zhuangqi
 * @@date 2017/3/14.
 */
@Service
public class SysRoleService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 所有的角色
     * @return
     */
    public List<SysRole> listRole() {
        return sysRoleMapper.selectAll();
    }

    /**
     * 根据用户Id得到用户关联角色列表
     * @param userId
     * @return
     */
    public List<SysUserRole> listRoleByUserId(String userId) {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(userId);
        return sysUserRoleMapper.select(sysUserRole);
    }

    /**
     * 新增角色
     * @param sysRole
     */
    public void saveRole(SysRole sysRole){
        SysRole role = new SysRole();
        role.setRoleId(UUIDUtil.getUUID());
        sysRoleMapper.insert(role);
    }

    /**
     * 保存用户角色
     * @param userId
     * @param roleId
     */
    public void saveUserRole(String userId, String roleId) {
        if (!this.userRoleValidate(userId,roleId)){
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setLsh(UUIDUtil.getUUID());
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            sysUserRole.setCreatTime(new Date());
        }
    }

    /**
     * 用户关联角色验证
     * @param userId
     * @param roleId
     * @return 存在TRUE、不存在FALSE
     */
    private boolean userRoleValidate(String userId,String roleId) {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(userId);
        sysUserRole.setRoleId(roleId);
        SysUserRole role = sysUserRoleMapper.selectOne(sysUserRole);
        if (ObjectUtils.isEmpty(role)){
            return false;
        }
        return true;
    }
}
